<script>
import axios from "../api/axios.config";
// import { useUserStore } from "@/stores/user";
// import { mapStores } from "pinia";
import { ElNotification } from "element-plus";
export default {
  data() {
    return {
      fileList: [],
      imgNames: [],
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  methods: {
    handleRemove(uploadFile, uploadFiles) {
      console.log(uploadFile, uploadFiles);
    },
    handlePictureCardPreview(uploadFile) {
      this.dialogImageUrl = uploadFile.url;
      this.dialogVisible = true;
    },
    handleSuccess(res) {
      this.imgNames.push(res.data); // 直接追加单个元素
      // console.log(this.imgNames);
    },
    handleError(err, file, fileList) {
      console.log(err, file, fileList);
      this.$message.error("上传失败：" + err.message);
    },
    // 新增：处理文件数量超限
    handleExceed(files, fileList) {
      this.$message.warning(
        `最多只能上传 5 张图片，您已选择了 ${files.length} 张图片，当前共有 ${fileList.length} 张图片`,
      );
    },
    toSubmit() {
      let len = this.fileList.length;
      if (len <= 0) {
        ElNotification({
          title: "Error",
          message: "至少添加一张图片",
          type: "error",
        });
        return false;
      }
      return true;
    },
    subImg(goods_id) {
      console.log(this.imgNames);
      this.imgNames.forEach((item,index) => {
        let url = "http://127.0.1:3006/images/goods/" + item;
        console.log(index,"  ==>  ",url);
        let datas = {
          goods_id: goods_id,
          url: url,
        };
        axios.post("/goods/addImg", datas);
      });
      this.imgNames = [];
      this.fileList = [];
    },
  },
};
</script>

<template>
  <section class="upImg">
    <el-upload
      action="/upfile"
      v-model:file-list="fileList"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :data="{ dir: 'goods' }"
      name="imgfile"
      :on-success="handleSuccess"
      :on-error="handleError"
      :limit="5"
      @exceed="handleExceed"
      :multiple="true"
    >
      <!-- 显示当前文件数量提示 -->
      <template v-if="fileList.length < 5">
        <el-icon><Plus /></el-icon>
      </template>
      <span v-else>已达上限</span>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </section>
</template>

<style scoped>
/* 上传区域样式 */
.upImg {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  background: #f5f7fa;
}

/* 调整上传卡片间距 */
:deep(.el-upload-list__item) {
  margin: 8px;
}
/* 新增：限制提示样式 */
.upImg :deep(.el-upload) {
  position: relative;
}

.upImg :deep(.el-upload span) {
  font-size: 12px;
  color: #999;
}
</style>
